﻿@page "/login"
@using Microsoft.AspNetCore.Components.Authorization
@using Rj.PersonnelVerification.Client.Server
@inject CustomAuthStateProvider AuthStateProvider
@inject NavigationManager Navigation
@inject IJSRuntime js
@layout LoginLayout
@inject IHttpClientFactory HttpFactroy



<div>
    <div Class="login-card">
    <MudCard>
        <MudCardContent>
            <MudText Typo="Typo.h6" Align="Align.Left" Style="font-size:larger">账号登录</MudText>

            <!-- 用户名输入框 -->
                <MudTextField @bind-Value="username" Label="在此输入您的工号" Variant="Variant.Filled"/>

            <!-- 密码输入框 -->
                <MudTextField @bind-Value="password" Label="请输入您的密码" Icon="@Icons.Material.Filled.Lock" Variant="Variant.Filled" InputType="InputType.Password" Adornment="Adornment.End" />
                @if (loginFailed)
                {
                    <p style="color: red;">登录失败！请重试</p>
                }
        </MudCardContent>
        <MudCardActions>
            <!-- 登录按钮 -->
                <MudButton Variant="Variant.Filled" FullWidth="true" Color="Color.Info" Style="background-color:#2468da" OnClick="LoginUser">登&nbsp;录</MudButton>
        </MudCardActions>
    </MudCard>
</div>

<div class="login-footer">
    ©&nbsp;上海太翼数字健康管理有限公司&nbsp;版权所有
</div>
</div>


@code {
    private string username;
    private string password;
    private bool loginFailed;

    private async Task LoginUser()
    {
        var loginModel = new { UserName = username, Pwd = password };
        var httpClient=HttpFactroy.CreateClient("ApiClient");
        var response = await httpClient.PostAsJsonAsync("api/auth/login", loginModel);

        if (response.IsSuccessStatusCode)
        {
            var token = await response.Content.ReadAsStringAsync();
            await js.InvokeVoidAsync("localStorage.setItem", "authToken", token);
            Navigation.NavigateTo("/");
        }
        else
        {
            loginFailed = true;
        }
    }
}
